package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    //新增的方法
    @PostMapping
    public R addCategory(@RequestBody Category category){
        //1、调用业务层的save方法进行保存
        boolean save = categoryService.save(category);
        return save?R.success("新增分类成功"):R.error("新增分类失败");
    }


    @GetMapping("/page")
    public  R queryPage( Integer page,Integer pageSize){
        IPage<Category> pageInfo = new Page<>(page,pageSize);
        categoryService.page(pageInfo);
        long all = pageInfo.getTotal();
        List<Category> re = pageInfo.getRecords();
        Map map = new HashMap();
        map.put("records",re);
        map.put("total",all);
        return R.success(map);
    }


    @DeleteMapping
    public R deleteById(Long id){
       R r =  categoryService.deleteById(id);
       return r;
    }


    @GetMapping("/list")
    public R list(Integer type){
        LambdaQueryWrapper<Category> qw = new LambdaQueryWrapper<>();
        qw.eq(type!=null,Category::getType,type);//where type = 1  2
        qw.orderByDesc(Category::getSort);
        List<Category> list = categoryService.list(qw);
        return R.success(list);
    }



}
